package opl.ui;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import opl.entities.Fixture;
import opl.ui.adapters.FixtureAdapter;
import opl.utilities.FileHelper;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

public class FixtureActivity extends Activity {

	private FixtureAdapter fixtureAdapter;
	private ListView lvFixtures;
	private List<Fixture> lstFixtures;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.fixture);

		lvFixtures = (ListView) findViewById(R.id.lvFixtures);
		lstFixtures = new ArrayList<Fixture>();
		fixtureAdapter = new FixtureAdapter(this, lstFixtures);
		lvFixtures.setAdapter(fixtureAdapter);
	}

	@Override
	protected void onStart() {
		super.onStart();
		RefreshFixtureList();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}

	private void RefreshFixtureList() {
		try {
			String jsonFixture = FileHelper.ReadFileAsString("fixture.txt",
					this);
			Type collectionType = new TypeToken<Collection<Fixture>>() {
			}.getType();
			Collection<Fixture> fixtures = new Gson().fromJson(jsonFixture,
					collectionType);
			lstFixtures.clear();
			lstFixtures.addAll(fixtures);
			fixtureAdapter.notifyDataSetChanged();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void imgTeamLogo_Click(View v) {
		LinearLayout ll = (LinearLayout) v.getParent();
		TextView tvName = (TextView) ll.getChildAt(1);
		Intent intTeam = new Intent(Intent.ACTION_VIEW,
				Uri.parse("opl://ui.team"));
		intTeam.putExtra("TeamName", tvName.getText());
		startActivity(intTeam);
	}

}